import 'package:flutter_application/pages/storage/novel_chapter_model.dart';
import 'package:sqflite_sqlcipher/sqflite.dart';

class DBManager {
  static const int version = 1;
  static Database? _database;
  static String currentUid = '';

  static _log(msg) {
    msg = 'SQL =》$msg';
    print('$msg');
  }

  static init(String userId) async {
    currentUid = userId;
    var databasePath = await getDatabasesPath();
    var path = '$databasePath/caches/$currentUid.db';

    _log("db path = $path");
    _database = await openDatabase(path, version: version, password: '1234',);
  }

  static Future<Database> getCurrentDatabase() async {
    if (_database == null) {
      await init(currentUid);
    }
    return _database!;
  }

  static isTableExists(String tableName) async {
    Database db = await getCurrentDatabase();
    String sql =
        "select * from Sqlite_master where type = 'table' and name = '$tableName' ";
    var res = await db.rawQuery(sql);
    return res.isNotEmpty;
  }

  static chapterTableName(int novelId) {
    return 'tbl_novel_$novelId';
  }

  static createChapterTable(int novelId) async {
    Database db = await getCurrentDatabase();
    var sql = '''
                CREATE TABLE IF NOT EXISTS ${chapterTableName(novelId)} (
                chapter_id INTEGER NOT NULL PRIMARY KEY,
                chapter_novel_id INTEGER NOT NULL,
                chapter_idx INTEGER NOT NULL,
                chapter_prev_id INTEGER NOT NULL,
                chapter_next_id INTEGER NOT NULL,
                chapter_title TEXT NOT NULL,
                chapter_content TEXT NOT NULL,
                create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
                ''';
    return await db.execute(sql);
  }

  static insertChapter(NovelChapterModel chapter) async {
    Database db = await getCurrentDatabase();
    return await db.insert(
        chapterTableName(chapter.novelId), chapter.toDBJson());
  }

  //查询缓存
  static Future<NovelChapterModel?> searchChapter(
      int novelId, int chapterId) async {
    Database db = await getCurrentDatabase();
    var result = await db.query(chapterTableName(novelId),
        where: 'chapter_id = ?', whereArgs: [chapterId]);
    if (result.isNotEmpty) {
      var data = result.first;
      return NovelChapterModel.fromDBJson(data);
    } else {
      return null;
    }
  }

  static updateChapter(int novelId) async {
    Database db = await getCurrentDatabase();
    return await db.update(chapterTableName(novelId), {"chapter_id":123},
                where: 'chapter_novel_id = ?', whereArgs: [novelId]);
  }

  //删除机制，多久没访问，就删除
  static deleteChapter(int novelId) async {
    Database db = await getCurrentDatabase();
    return await db.delete(chapterTableName(novelId));
  }

  static close() {
    if (_database != null) {
      if (_database!.isOpen) {
        _database!.close();
      }
    }
    _database = null;
  }
}
